﻿using ldc_mvc_closing_hwk.Models.Database;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;
using Microsoft.AspNetCore.Razor.Language.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace ldc_mvc_closing_hwk.Controllers
{

    [Route("[action].html")]
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        private readonly LdcFASContext _db;

        public HomeController(LdcFASContext db)
        {
            _db = db;
        }

        const int PAGE_SIZE = 6;
        [Route("/")]
        [Route("/Index.html")]
        [Route("/Index_{tagFilter}.html")]
        public IActionResult Index(int? tagFilter, string keyWord, int page = 1)
        {
            var tagList = _db.ArticleAreas.ToList();
            ViewBag.TagList = tagList;

            int skip = PAGE_SIZE * (page - 1);
            var articleMeta = _db.ArticleMeta;
            var filterPage = articleMeta.AsQueryable();
            //  搜索过滤
            if (keyWord != null)
            {
                filterPage = filterPage.Where(x => x.Title.Contains(keyWord) || x.Summary.Contains(keyWord));
            }
            // 标签过滤
            if (tagFilter != null)
            {
                filterPage = filterPage.Where(x => x.FkAreaId == tagFilter);
            }

            // 分页查询
            ViewBag.ArticleList = filterPage.Skip(skip).Take(PAGE_SIZE).ToList();
            ViewBag.PageCount = (int)Math.Max(Math.Ceiling((double)filterPage.Count() / PAGE_SIZE ), 1);
            ViewBag.CurrentPage = page;
            return View();
        }

        [Route("/detail_{metaId}.html")]
        public IActionResult Detail(int metaId)
        {
            var tagList = _db.ArticleAreas.ToList();
            ViewBag.TagList = tagList;

            ViewBag.ArticleMeta = _db.ArticleMeta.Where(x => x.Id == metaId).First();

            ViewBag.ArticleContent = _db.ArticleContents.Where(x=> x.FkArticleMeta == metaId).First();

            return View();
        }
    }
}
